import React, { useEffect, useState } from 'react'
import { NavBar, Input, Button } from '@nutui/nutui-react'
import { ArrowLeft } from '@nutui/icons-react'
import { useNavigate, useLocation } from 'react-router-dom'
import { verifyCodeTow,setPwd } from '../../../request/instance'
import { Toast } from '@nutui/nutui-react'
const regex = new RegExp(/^[0-9]{6}$/)
export default function PayPwd() {
  const marginStyle = {
    margin: "50px auto", width: '90%', background: "#97b97f", display: 'flex',
    justifyContent: 'center',
  }
  let navigate = useNavigate()
  let {state:{phone,_id,code}} = useLocation()
  

  const [newPwd, setnewPwd] = useState('')
  const [newPwd2, setnewPwd2] = useState('')

  let verify = async () => {
    let res = await verifyCodeTow({ code,_id })
    res.data.code !== 200 && navigate('/setpwd')
  }

  // 对验证码进行再次验证
  useEffect(() => {
    verify()
  }, [])
  // 确定修改密码进行修改
  const setPwd1 = async () => {
    if (newPwd === newPwd2) {

      if (regex.test(newPwd)) {
        // 向后端发送修改密码的请求
        let res = await setPwd({ newPwd, _id })
        if(res.data.code === 200){
          Toast.show({
            icon: 'success',
            content: '修改成功',
            position: 'center',
          })
          navigate('/show/mine')
        }
      } else {
        Toast.show({
          content: '请输入6位的密码',
          icon: 'fail',
        })
      }
    } else {
      Toast.show({
        content: '两次密码不一致',
        icon: 'fail',
      })
    }
  }
  return (
    <div>
      <NavBar
        back={<ArrowLeft />}
        onBackClick={(e) => navigate('/show/mine')}
      >确认支付密码</NavBar>
      <div className='pay-pwd'>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            background: '#fff',
            padding: '0 10px',
          }}>
          <span className='verification' style={{ marginRight: "0.5rem" }}>
            密码
          </span>
          <Input
            placeholder="请输入新密码"
            style={{ '--nutui-input-padding': '10px' }}
            value={newPwd}
            onChange={(e) => setnewPwd(e)}
          />
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            background: '#fff',
            padding: '0 10px',
          }}>
          <span className='verification'>
            确认密码
          </span>
          <Input
            placeholder="请输入新密码"
            style={{ '--nutui-input-padding': '10px' }}
            value={newPwd2}
            onChange={(e) => setnewPwd2(e)}
          />
        </div>

      </div>
      <Button style={marginStyle} type="primary" shape="square"
        onClick={setPwd1}
      >
        确定
      </Button>

    </div>
  )
}
